<?php

/**
 * FilesystemTools
 *
 * @author Eugene I. Nezhuta
 */
class RCMS_Tools_FilesystemTools {

/**
 * This function returns content of file.
 * @param string $filePath
 * @return string
 */
	public static function getFile($filePath) {
		if(!file_exists($filePath)) {
			throw new Exception('Can\'t find' . $filePath . ' file or this file doesn\'t exist');
		}
		return file_get_contents($filePath);
	}

	/**
	 * This function saves content into a file.
	 * @param string $filePath
	 * @param string $fileContent
	 * @return boolean
	 */
	public static function saveFile($filePath, $fileContent) {
		if(false === file_put_contents($filePath, $fileContent)) {
			throw new Exception('Can\'t save file: '. $filePath . ' Something went wrong');
		}
		return true;
	}

	/**
	 * This function deletes a file.
	 * @param string $fileName
	 * @return boolean
	 */
	public static function deleteFile($fileName) {
		$fileName = (string) trim($fileName);

		if($fileName === '') {
			return false;
		}

		if(file_exists($fileName)) {
			return @unlink($fileName);
		}
		else {
			return false;
		}

	}

	/**
	 * This function is validated files name.
	 * @param string $fileName
	 * @return string
	 */
	public static function validateName($name) {
		$name = (string) trim($name);
		if($name === '') {
			return '';
		}
		$name = str_replace(' ', '-', $name);
		return strtolower(preg_replace("/[\s\$\#\%\<\>\.\*\&\(\)\}\{\+\,\=\/\|\?\@\!\~\^\:\'\"\[\]\_\\\]/", '', $name));

	}

	/**
	 * This function are scaning a directory and returns array of files.
	 * @param string $path
	 * @return array
	 */
	public static function scanDir($path) {
		$path = (string) trim($path);
		$files = array();

		if($path === '') {
			return $files;
		}

		if(is_dir($path)) {
			$dir = @scandir($path);
			if(empty($dir)) {
				return array();
			}

			foreach($dir as $file) {
				if(!preg_match('~^\..*$~', $file)) {
				//if($file !== '.' && $file !== '..' && $file !== '.svn' && $file !== '.htaccess')
					$files[] = $file;
				}
			}
		}
		return $files;
	}

	/**
	 * This function creates a directory.
	 * @param string $pathName
	 * @return boolean
	 */
	public static function mkDir($pathName) {
		$pathName = (string) trim($pathName);

		if($pathName === '') {
			return false;
		}

		if(!is_dir($pathName)) {
			return @mkdir($pathName);
		}
		else {
			return false;
		}
	}

	/**
	 * This function is removing a directory.
	 * @param string $dirName
	 * @return boolean
	 */
	public static function rmDir($dirName) {
		$dirName = (string) trim($dirName);

		if($dirName === '') {
			return false;
		}

		if(is_dir($dirName)) {
			return @rmdir($dirName);
		}
		else {
			return false;
		}
	}

	/**
	 * This function deletes a lot of spaces.
	 * @param string $string
	 * @return string
	 */
	public static function trimInternalSpaces($string) {
		if($string) {
			$pattern = "/[\s]+/";
			return preg_replace($pattern, " ", trim($string));
		}
	}

	/**
	 * This function checks if a file exists.
	 * 
	 * @param string $filePath
	 * @return boolean
	 */
	public static function isFileExists($filePath) {
		return file_exists($filePath);
	}

	/**
	 * This function finds files where type of files equal $ext.
	 * 
	 * @param string $dir
	 * @param string $ext
	 * @return array or boolean
	 */
	public static function findFilesByExt($dir, $ext) {
		$extFiles = array();
		$files = array();
		$files = self::scanDir($dir);
		if(!empty($files)) {
			foreach ($files as $file) {
				if(preg_match('/^[a-zA-Z0-9-_\s]+\.'.$ext.'$/', $file)) {
					$extFiles[] = $file;
				}
			}
			if(!empty ($extFiles)) {
				return $extFiles;
			}
		}
		return false;
	}

	/**
	 *
	 * @param string $themeName
	 * @return void
	 */
	public static function createZip($themeName) {
		$websitePath  = unserialize(Zend_Registry::get('config'))->website->website->path;
		$websiteUrl = unserialize(Zend_Registry::get('config'))->website->website->url;
		ini_set('max_execution_time', 300);
		// create object
		$zip = new ZipArchive();
		// open archive
		if(is_file($websitePath.'themes/'.$themeName.'/'.$themeName.'.zip')) {
			@unlink($websitePath.'themes/'.$themeName.'/'.$themeName.'.zip');
		}
		if ($zip->open($websitePath.'themes/'.$themeName.'/'.$themeName.'.zip', ZIPARCHIVE::CREATE) !== TRUE) {
			die ('Could not open archive');
		}

		$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($websitePath.'themes/'.$themeName));

		foreach ($iterator as $key=>$value) {
			$zip->addFile($key, strstr($key,$themeName)) or die ('ERROR: Could not add file: $key');
		}
		// close and save archive
		$zip->close();
		return $websiteUrl.'themes/'.$themeName.'/'.$themeName.'.zip';
	}

	public static function normalize ($string,$pageId) {

		$table = array(
			'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
			'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
			'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
			'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
			'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
			'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
			'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
			'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
		);
		$string = preg_replace('/[^_A-Za-z0-9\.\s]/','',strtr($string, $table));
		if(trim($string) == '') {
			$string = $pageId;
		}
		return $string;
	}

	 public static function cutStringOnWords($cuttedString,$length){
		$substr = substr($cuttedString, 0, $length);
		$arr = explode(" ", $substr);
		$arrLen = sizeof($arr);

		if($arr[$arrLen-1]!='' || $arr[$arrLen-1]!=" "){
			$arr[$arrLen-1] = '';
		}
		return implode(" ", $arr);
	 }

     public static function getDirectories($path)
     {
        $path = trim($path);
		$dirs = array();

		if ($path == '') {
			return $dirs;
		}

		if (is_dir($path)) {
			$dir = @scandir($path);
			if (empty($dir)) {
				return array();
			}
			foreach ($dir as $file) {
				if ($file !== '.' && $file !== '..' && $file !== '.svn' && $file !== '.htaccess' && is_dir($path.$file)) {
					$dirs[] = $file;
                }
			}
		}
        return $dirs;
     }

	public static function removeSWFUploadTempFiles() {
		$path = 'tmp/';
		$files = scandir($path);
		foreach ($files as $file) {
			if(preg_match('/^[0-9]+\.[a-zA-Z]{3}$/', $file) && !is_dir($file)) {
				@unlink($path . $file);
			}
		}
	}

	public static function createMediaListForTinyMce() {
		$mediaListFile = 'system/js/tiny_mce/medialist.js';
		if(file_exists($mediaListFile)) {
			$videoFiles = self::findFilesByExt('downloads/', '(swf|flv|avi|mov|mpeg)');
			if($videoFiles && !empty ($videoFiles)) {
				$mediaListString = 'var tinyMCEMediaList = [';
				foreach ($videoFiles as $file) {
					$mediaListString .= '["' . $file . '", "downloads/'. $file .'"],';
				}
				$mediaListString = rtrim($mediaListString, ',') . ']';
				@file_put_contents($mediaListFile, $mediaListString);
			}
		}
	}
}